package com.cadre.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cadre.common.core.domain.entity.SysUser;
import com.cadre.common.utils.bean.BeanUtils;
import com.cadre.common.utils.oldutil.PoiUtil;
import com.cadre.system.domain.TeamOperation;
import com.cadre.system.domain.officer.*;
import com.cadre.system.domain.officer.config.B01XmlOutVO;
import com.cadre.system.mapper.*;
import com.cadre.system.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/system/xml")
public class SysOutXmlController {

    @Resource
    private A01Service a01Service;
    @Resource
    private A01Mapper a01Mapper;
    @Resource
    private A12Service a12Service;
    @Resource
    private A25Mapper a25Service;
    @Resource
    private A27Service a27Service;
    @Resource
    private A93Service a93Service;
    @Resource
    private PxRypxxxService pxRypxxxService;
    @Resource
    private RetirementService retirementService;
    @Resource
    private A16Service a16Service;
    @Resource
    private A17Service a17Service;
    @Resource
    private A19Service a19Service;
    @Resource
    private A22Service a22Service;
    @Resource
    private A26Service a26Service;
    @Resource
    private A79Service a79Service;
    @Resource
    private A91Service a91Service;
    @Resource
    private A92Service a92Service;


    @Resource
    private ISysUserService systemUserService;
    @Resource
    private UnitInfoService unitInfoService;

    @Resource
    private B01Mapper b01Service;
    @Resource
    private B04Service b04Service;
    @Resource
    private B41Service b41Service;
    @Resource
    private B50Mapper b50Mapper;

    @Resource
    private  SysConfigService systemConfigService;

    @Resource
    private RosterService rosterService;

    @GetMapping("/a01")
    public ResponseEntity getA01Xml() {
        // 指定文件路径
        String filePath = "/usr/local/cadre/a01.json";
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 可选：美化输出

        try (FileWriter fileWriter = new FileWriter(filePath ,true)) {
            fileWriter.write("{\"a01XmlOutVOS\": ["); // 写入文件头

            boolean isFirstBatch = true;
            for (int i = 0; true; i += 100) {
                List<A01> list = a01Mapper.getAll(i); // 每次查询100条
                if (list.isEmpty()) {
                    break; // 如果查询结果为空，停止循环
                }

                List<A01XmlOutVO> a01XmlOutVOS = new ArrayList<>();
                for (A01 a01 : list) {
                    String flowid = a01.getFlowid();
                    List<A12> a12List = a12Service.list(new LambdaQueryWrapper<A12>().eq(A12::getPersonid, flowid));
                    List<A16> a16List = a16Service.list(new LambdaQueryWrapper<A16>().eq(A16::getPersonid, flowid));
                    List<A17> a17List = a17Service.list(new LambdaQueryWrapper<A17>().eq(A17::getPersonid, flowid));
                    List<A19> a19List = a19Service.list(new LambdaQueryWrapper<A19>().eq(A19::getPersonid, flowid));
                    List<A22> a22List = a22Service.list(new LambdaQueryWrapper<A22>().eq(A22::getPersonid, flowid));
                    List<A25> a25List = a25Service.selectList(new LambdaQueryWrapper<A25>().eq(A25::getPersonid, flowid));
                    List<A26> a26List = a26Service.list(new LambdaQueryWrapper<A26>().eq(A26::getPersonid, flowid));
                    List<A27> a27List = a27Service.list(new LambdaQueryWrapper<A27>().eq(A27::getPersonid, flowid));
                    List<A79> a79List = a79Service.list(new LambdaQueryWrapper<A79>().eq(A79::getPersonid, flowid));
                    List<A91> a91List = a91Service.list(new LambdaQueryWrapper<A91>().eq(A91::getPersonid, flowid));
                    List<A92> a92List = a92Service.list(new LambdaQueryWrapper<A92>().eq(A92::getPersonid, flowid));
                    List<A93> a93List = a93Service.list(new LambdaQueryWrapper<A93>().eq(A93::getPersonid, flowid));
                    List<PxRypxxxEntity> pxRypxxxEntities = pxRypxxxService.list(new LambdaQueryWrapper<PxRypxxxEntity>().eq(PxRypxxxEntity::getPersonid, flowid));
                    List<Retirement> retirements = retirementService.list(new LambdaQueryWrapper<Retirement>().eq(Retirement::getFlowid, flowid));

                    A01XmlOutVO a01XmlOutVO = new A01XmlOutVO();
                    if(null != a01.getA0171() && a01.getA0171().length > 0) {
                        imgDown(flowid, a01.getA0171());
                        a01.setA0171(null);
                    }
                    BeanUtils.copyProperties(a01, a01XmlOutVO);
                    a01XmlOutVO.setA12List(a12List);
                    a01XmlOutVO.setA16List(a16List);
                    a01XmlOutVO.setA17List(a17List);
                    a01XmlOutVO.setA19List(a19List);
                    a01XmlOutVO.setA22List(a22List);
                    a01XmlOutVO.setA25List(a25List);
                    a01XmlOutVO.setA26List(a26List);
                    a01XmlOutVO.setA27List(a27List);
                    a01XmlOutVO.setA79List(a79List);
                    a01XmlOutVO.setA91List(a91List);
                    a01XmlOutVO.setA92List(a92List);
                    a01XmlOutVO.setA93List(a93List);
                    a01XmlOutVO.setPxRypxxxEntities(pxRypxxxEntities);
                    a01XmlOutVO.setRetirements(retirements);
                    a01XmlOutVOS.add(a01XmlOutVO);
                }

                // 将对象转换为 JSON 字符串
                String jsonString = objectMapper.writeValueAsString(a01XmlOutVOS);

                if (!isFirstBatch) {
                    fileWriter.write(","); // 如果不是第一个批次，写入逗号分隔符
                }
                fileWriter.write(jsonString);

                isFirstBatch = false;

                // 清理内存
                list.clear();
                a01XmlOutVOS.clear();
            }

            fileWriter.write("]}"); // 写入文件尾

            // 返回成功响应
            return ResponseEntity.ok("JSON data written to file successfully");

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error writing JSON to file");
        }
    }

    @Async
    protected void imgDown(String flowid , byte[] img){
        //将二进制图片转化为图片，图片名字是flowid.jpg，保存在/usr/local/cadre/pic/flowid.jpg
        // 定义文件保存路径
        String directoryPath = "/usr/local/cadre/pic/";
        String filePath = directoryPath + flowid + ".jpg";

        // 创建目录（如果不存在）
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            if (!created) {
                System.err.println("无法创建目录: " + directoryPath);
                return;
            }
        }

        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            // 将二进制数据写入文件
            fos.write(img);
            System.out.println("图片已成功保存到: " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("保存图片时发生错误: " + e.getMessage());
        }
    }


    @GetMapping("/b01")
    public ResponseEntity getB01Xml(){
        //单位信息
        List<B01> b01s = b01Service.selectByMaps(new HashMap<>());
        List<B01XmlOutVO> b01XmlOutVOS = new ArrayList<>();
        b01s.stream().forEach(b01 -> {
            B01XmlOutVO b01XmlOutVO = new B01XmlOutVO();
            List<B04> b04List = b04Service.list(new LambdaQueryWrapper<B04>().eq(B04::getUnitid, b01.getFlowid()));
            List<B41> b41List = b41Service.list(new LambdaQueryWrapper<B41>().eq(B41::getUnitid, b01.getFlowid()));
            List<B50> b50List = b50Mapper.selectByUnitFlowId(b01.getFlowid());
            List<TeamMember> teamMembers = unitInfoService.getteamMembers(b01.getFlowid());
            BeanUtils.copyProperties(b01, b01XmlOutVO);
            b01XmlOutVO.setB04List(b04List);
            b01XmlOutVO.setB41List(b41List);
            b01XmlOutVO.setTeamMembers(teamMembers);
            b01XmlOutVO.setB50List(b50List);
            b01XmlOutVOS.add(b01XmlOutVO);
        });
        try {
            // 创建 ObjectMapper 实例
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 可选：美化输出

            // 将对象转换为 JSON 字符串
            String jsonString1 = "{\"b01XmlOutVOS\":" + objectMapper.writeValueAsString(b01XmlOutVOS)+ "}";
            // 将 JSON 数据写入文本文件
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            outputStream.write(jsonString1.getBytes());
            outputStream.write("\n".getBytes());

            // 创建响应
            InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(outputStream.toByteArray()));
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=B01.json")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error writing JSON to file");
        }

    }
    @GetMapping("/sys")
    public ResponseEntity getSysXml(){
        //智搜信息
        List<SysConfigEntity> list1 = systemConfigService.list();
        try {
            // 创建 ObjectMapper 实例
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 可选：美化输出

            // 将对象转换为 JSON 字符串
            String jsonString3 = "{\"ISysConfig\":" + objectMapper.writeValueAsString(list1)+ "}";
            // 将 JSON 数据写入文本文件
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            outputStream.write(jsonString3.getBytes());

            // 创建响应
            InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(outputStream.toByteArray()));
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=sys.json")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error writing JSON to file");
        }

    }

    @GetMapping("/sysUsers")
    public ResponseEntity getSysUsersXml(){
        //用户信息
        List<SysUser> sysUsers = systemUserService.selectAll();
        try {
            // 创建 ObjectMapper 实例
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 可选：美化输出

            // 将对象转换为 JSON 字符串
            String jsonString2 = "{\"sysUsers\":" + objectMapper.writeValueAsString(sysUsers)+ "}";
            // 将 JSON 数据写入文本文件
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            outputStream.write(jsonString2.getBytes());

            // 创建响应
            InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(outputStream.toByteArray()));
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=sysUsers.json")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error writing JSON to file");
        }

    }

    @GetMapping("/roster")
    public ResponseEntity getRoster(){
        //花名册
        List<Roster> list = rosterService.list();
        list.stream().forEach(roster -> {
            List<A01> a01s = a01Service.listByIds(Arrays.asList(roster.toString().split(",")));
            roster.setA01(a01s);
        });
        try {
            // 创建 ObjectMapper 实例
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 可选：美化输出

            // 将对象转换为 JSON 字符串
            String jsonString2 = "{\"roster\":" + objectMapper.writeValueAsString(list)+ "}";
            // 将 JSON 数据写入文本文件
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            outputStream.write(jsonString2.getBytes());

            // 创建响应
            InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(outputStream.toByteArray()));
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=sysUsers.json")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error writing JSON to file");
        }

    }


}
